#!/usr/bin/env python
# @file context.py


import logging
import os
import sys

import object
from common_helpers import *

class Context:
    def __init__(self):
        from environment import Environment
        from watch import Watch

        self._dents = {}
        self.symbols = object.Object(
            items = {
                'env': Environment(),
            }
        )

        try:
            import pyinotify

            self.watch = {
                os.getcwdu(): Watch(self, os.getcwdu()),
            }
        except ImportError:
            self.watch = None

        self._parse()

    def prompt(self):
        return str(self.symbols['env']['prompt'])

    def order(self, cmd, *args):
        return self.symbols['env']['orders'][cmd](self, cmd, *args)

    def update_dents(self, dir):
        raise NotImplementedError

    def write(self, msg):
        self._parse_context.append_output(msg)
        self._parse_context.flush()

    def _parse(self):
        """
        Initializes an instantiation-internal parse context as either an
        interactive or non-interactive session based on whether or not the
        current stdin is a valid terminal.

        TODO: document exceptions that are caught
        """

        from interactive_session import InteractiveSession
        from noninteractive_session import NoninteractiveSession
        from parse_context import DoneParsing

        try:
            # Note that os.isatty is only available on POSIX compliant systems.
            #
            # Varix as it stands can only support POSIX, as it depends
            # on things like termios and pwd, which have no real analogs
            # on some other platforms. --toc
            if os.isatty(sys.stdin.fileno()):
                self._parse_context = InteractiveSession(self)
            else:
                self._parse_context = NoninteractiveSession(self)
        except DoneParsing:
            logging.info('%s finished parsing' % classname(self))
        except KeyboardInterrupt:
            logging.info('%s got a keyboard interrupt' % classname(self))
